'use strict';
const db = uniCloud.database()
// 聚合操作符
const $ = db.command.aggregate
// 查询条件操作符
const dbCmd = db.command

exports.main = async (event, context) => {
	
	const {
		user_id,
		article_id,
		content,
		comment_id = '', // 评论 id
		reply_id = '',
		is_reply = false
	} = event
	
	let user = await db.collection('user').doc(user_id).get()
	user = user.data[0]
	
	// 获取文章内容
	let article = await db.collection('article').doc(article_id).get()
	// 获取所有的评论内容
	const comments = article.data[0].comments
	
	// 评论信息
	let commentObj = {
		comment_id: getId(6),	// 评论 id
		comment_content: content, // 评论内容
		create_time: new Date().getTime(), // 创建时间
		is_reply: is_reply, // 判断是主回复还是子回复
		author: {
			author_id: user._id,
			author_name: user.author_name,
			avatar: user.avatar,
			professional: user.professional // 专业
		},
		reply: [] // 评论回复
	}
	
	if(comment_id === '') {
		commentObj.reply = []
		// 评论文章
		commentObj = dbCmd.unshift(commentObj)
	}else {
		// 回复评论
		// 获取评论索引
		let commentIndex = comments.findIndex(item => item.comment_id === comment_id)
		
		// 获取作者信息
		let commentAuthor = ''
		
		if(is_reply) {
			// 子回复
			commentAuthor = comments[commentIndex].reply.find(item => item.comment_id === reply_id)
		}else {
			// 主回复
			commentAuthor = comments.find(item => item.comment_id === comment_id)
		}
		commentAuthor = commentAuthor.author.author_name
		commentObj.to = commentAuthor
		
		// 更新评论内容
		commentObj = {
			[commentIndex]: {
				reply: dbCmd.unshift(commentObj)
			}
		}
	}
	
	await db.collection('article').doc(article_id).update({
		comments: commentObj
	})
	
	//返回数据给客户端
	return {
		code: 200,
		msg: '数据更新成功'
	}
};

function getId(length) {
	return Number(Math.random().toString().substr(3,length)+Date.now()).toString(36)
}